﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.Framework;
using Web.CrmContacto.Code;
using Web.CrmContacto.Code.Security;
using CrmContacto.Contracts.Contracts;
using System.Web.UI.HtmlControls;
using CrmContacto.WebApp.Code.InnerClasses;
using Web.Framework.Translate;
using Web.Framework.Misc;
using System.Web.Caching;
using System.Reflection;
using System.Configuration;
using System.IO;
using CrmContacto.Contracts.Enums;


namespace Web.CrmContacto
{
    public partial class SiteMaster : BaseMasterPage
    {
        public override void PreLoad()
        {
            base.PreLoad();
            this.pnlMessages.CssClass = "pnlMessagesClass displayNone";
            this.txtMessages.Text = string.Empty;
            BuildMenu();

            LoginStatus status = (LoginStatus)HeadLoginView.FindControl("HeadLoginStatus");
            if (status != null)
            {
                status.LoggedOut += new EventHandler(LoginStatusEvent_LoggedOut);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.Page.User.Identity.IsAuthenticated)
                {
                    Label loginName = (Label)this.HeadLoginView.FindControl("lblLoginName");
                    loginName.Text = BaseWebPage.DisplayUserName;

                    if (HttpContext.Current.Session[MiscClass.SessionJustLogin] != null)
                    {
                        bool justLogin = (bool)HttpContext.Current.Session[MiscClass.SessionJustLogin];
                        if (justLogin)
                        {
                            RegistrarPopupInterfaceDeVentas();
                            // Cambio el valor para que no muestre el popup
                            HttpContext.Current.Session[MiscClass.SessionJustLogin] = false; 
                        }
                    }

                }

                List<string> cookieCompany = HttpHelper.GetCookieValues(MiscClass.CookieCompany, this.Request);

                if (cookieCompany.Count > 1)
                {
                    int companyId = Convert.ToInt32(cookieCompany[0]);
                    CustomizeCompanyLookAndFeel(companyId);

                    Control ctrlBienvenido = this.HeadLoginView.FindControl("lblPtoVtaBienvenido");
                    if (ctrlBienvenido != null)
                    {
                        Label lblBienvendioPtoVta = (Label)ctrlBienvenido;
                        lblBienvendioPtoVta.Text = Server.HtmlEncode(cookieCompany[1]);
                    }

                    LoadCustomerStadistics(companyId);

                    if (!this.IsPostBack)
                    {
                        SetVersion();
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void RegistrarPopupInterfaceDeVentas()
        {
            // Muestro el popup, registro una variable que luego en el onload se revisa y se hace un alert
            ResultadoInterfaceVentas resultadoInterface = WebServiceHelper.GetResultadoInterfaceVentas(BaseWebPage.CompanyId);

            // Analizo el resultado para ver si muestro el mensaje
            bool mostrarMensaje = false;

            string textoMensaje = string.Empty;
            // Si no hay valor es que no existía el registro
            if (!resultadoInterface.EjecutoOK.HasValue)
            {
                mostrarMensaje = true;
                textoMensaje = LocalizationProvider.Instance["Bo.InterfaceVentas.SinInformacion"];
            }
            else
            {            
                // Puede ser un registro viejo o se ejecutó ok o no ok
                TimeSpan span = DateTime.Now - resultadoInterface.FechaUltimaCorrida.Value;
                if (span.TotalDays > 1.5)
                {
                    mostrarMensaje = true;
                    textoMensaje = string.Format(LocalizationProvider.Instance["Bo.InterfaceVentas.FechaAntigua"], resultadoInterface.FechaUltimaCorrida);
                }
                else
                {
                    if (!resultadoInterface.EjecutoOK.Value)
                    {
                        mostrarMensaje = true;
                        textoMensaje = string.Format(LocalizationProvider.Instance["Bo.InterfaceVentas.EjecucionFallo"], resultadoInterface.FechaUltimaCorrida);
                    }
                }
            }

            if (mostrarMensaje)
            {
                litPopUpInterfaceVentas.Text = string.Format("<div id='showMessageInterfaceVentas' title='{0}'><p>{1}</p></div>",LocalizationProvider.Instance["Bo.InterfaceVentas.Titulo"], textoMensaje);
                Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptJustLogin", "<script type='text/javascript'> window.justLogin = true; </script>");
            }
        }

        private void SetVersion()
        {
            string oVersionNumero = Convert.ToString(StoreHelper.GetObject("versionNumero"));
            string oVersionText = Convert.ToString(StoreHelper.GetObject("versionTexto"));

            if (String.IsNullOrEmpty(oVersionNumero))
            {
                oVersionNumero = Assembly.GetExecutingAssembly().GetName().Version.ToString();
                StoreHelper.StoreObject("versionNumero", oVersionNumero);
            }

            if (String.IsNullOrEmpty(oVersionText))
            {
                string path = ConfigurationManager.AppSettings["VersionTextPath"];
                oVersionText = File.ReadAllText(path);
                StoreHelper.StoreObject("versionTexto", oVersionText);
            }

            this.lblAppVersion.Text = LocalizationProvider.Instance["Bo.Version.Numero"] + oVersionNumero;
            this.lblAppText.Text = LocalizationProvider.Instance["Bo.Version.Fecha"] + oVersionText;
        }

        private void LoadCustomerStadistics(int companyId)
        {
            if (Page.User.Identity.IsAuthenticated)
            {
                DateTime now = DateTime.Now;
                DateTime mesEnCurso = new DateTime(now.Year, now.Month, 1);
                var cantidades = WebServiceHelper.GetCantidadDeContactos(companyId, mesEnCurso);

                lblCustomerStadistics.Text = string.Format(LocalizationProvider.Instance["TopBar.CantidadDeContactos"], cantidades.CantidadDeContactosTotales, cantidades.CantidadContactosMesEnCurso);
            }
            else
            {
                lblCustomerStadistics.Text = string.Empty;
            }
        }

        private void CustomizeCompanyLookAndFeel(int companyId)
        {
            CompanyConfiguration companyConfiguration = BasePage.GetCompanyConfigurationList(this.Page).Where(c => c.CompanyId == companyId).SingleOrDefault();
            if (companyConfiguration != null)
            {
                if (!String.IsNullOrEmpty(companyConfiguration.CssFilePath))
                {
                    HtmlLink myHtmlLink = new HtmlLink();
                    myHtmlLink.Href = string.Format("/Styles/Company/{0}", companyConfiguration.CssFilePath);
                    myHtmlLink.Attributes.Add("rel", "stylesheet");
                    myHtmlLink.Attributes.Add("type", "text/css");
                    Page.Header.Controls.Add(myHtmlLink);
                }

                if (!String.IsNullOrEmpty(companyConfiguration.LogoImgFilePath))
                {
                    this.ImgEmpresa.ImageUrl = companyConfiguration.LogoImgFilePath;
                }
            }
            else
            {
                this.ImgEmpresa.CssClass = "displayNone";
            }
        }

        public override void ShowMessage(string message, WebMessageType type)
        {
            ShowMessage(LocalizationProvider.Instance["Bo.Messages.Mensaje"], message, type);
        }

        public override void ShowMessage(string title, string message, WebMessageType type)
        {
            this.pnlMessages.CssClass = "pnlMessagesClass displayBlock";
            this.txtErrorTitle.Text = title;
            this.txtMessages.Text = message;
            if (type != WebMessageType.Error)
            {
                pnlError.CssClass = "errorPanelMessage";
            }
            else
            {
                pnlError.CssClass = "errorPanelError";
            }
        }

        public override void MakeMenuVisible(bool visible)
        {
            this.NavigationMenu.Visible = visible;
            fl_menu_cmd.Visible = visible;
        }

        private void LoginStatusEvent_LoggedOut(Object sender, System.EventArgs e)
        {
            try
            {
                Session.Clear();
                Session.Abandon();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        public override void LoadContextActions(List<LinkButton> linkButtons)
        {
            //<a href="#" class="menu_item_cmd">Crear Lista de Distribución</a>
            foreach (LinkButton lnkCtrl in linkButtons)
            {
                if (lnkCtrl.CssClass == null)
                {
                    lnkCtrl.CssClass = string.Empty;
                }

                lnkCtrl.CssClass = lnkCtrl.CssClass + " menu_item_cmd";
                this.pnlActionsMenu.Controls.Add(lnkCtrl);
            }

        }

        private void AddReporteToMenu(MenuItem menuParent, ReportingConfiguration reporteConfig)
        {
            if (reporteConfig != null)
            {
                if (!String.IsNullOrEmpty(reporteConfig.ReportAppUrl))
                {
                    if (HasPermissionFor(reporteConfig.SecurityKey))
                    {
                        MenuItem ReporteVentasPorClienteMenu = new MenuItem()
                        {
                            NavigateUrl = reporteConfig.ReportAppUrl,
                            Text = LocalizationProvider.Instance[reporteConfig.LocalizationKey]
                        };

                        menuParent.ChildItems.Add(ReporteVentasPorClienteMenu);
                    }
                }
                else if (HasPermissionFor(reporteConfig.SecurityKey))
                {
                    MenuItem ReporteOperacionesMenu = new MenuItem()
                    {
                        NavigateUrl = string.Format("~/App/ReportingService.aspx?Reporte={0}", reporteConfig.Nombre),
                        Text = LocalizationProvider.Instance[reporteConfig.LocalizationKey]
                    };

                    menuParent.ChildItems.Add(ReporteOperacionesMenu);
                }
            }
        }

        private string formatReporte(string lang, string reportName)
        {
            return string.Format(reportName, lang);
        }

        public override void BuildMenu()
        {
            List<ReportingConfiguration> reportingConfigurationList = BasePage.GetReportingConfiguration(this.Application);

            string paisPorDefecto = ConfigurationManager.AppSettings["LenguajePorDefecto"];
            this.NavigationMenu.DynamicEnableDefaultPopOutImage = true;

            if (this.NavigationMenu.Visible)
            {
                MenuItem SearchCustomer = new MenuItem()
                {
                    NavigateUrl = "~/App/CustomerSearch.aspx",
                    Text = LocalizationProvider.Instance["Bo.Menu.Contactos"]
                };

                this.NavigationMenu.Items.Add(SearchCustomer);

                SearchCustomer.Selectable = HasPermissionFor(CrmSecurity.CUSTOMERSEARCH_VIEW);

                if (HasPermissionFor(CrmSecurity.CUSTOMERSEARCH_VIEW))
                {
                    MenuItem SearchCustomer2 = new MenuItem()
                    {
                        NavigateUrl = "~/App/CustomerSearch.aspx",
                        Text = LocalizationProvider.Instance["Bo.Menu.Contactos"]
                    };

                    SearchCustomer.ChildItems.Add(SearchCustomer2);
                }

                if (HasPermissionFor(CrmSecurity.CUSTOMER_CREATE))
                {
                    MenuItem AddCustomer = new MenuItem()
                    {
                        NavigateUrl = "~" + MiscClass.UrlCustomerEdit,
                        Text = LocalizationProvider.Instance["Bo.SearchContacto.CmdCrearContacto"]
                    };

                    SearchCustomer.ChildItems.Add(AddCustomer);
                }

                if (HasPermissionFor(CrmSecurity.CUSTOMER_IMPORT))
                {
                    MenuItem ImportarContactosMenu = new MenuItem()
                    {
                        NavigateUrl = "~" + MiscClass.UrlImportarContactos,
                        Text = LocalizationProvider.Instance["Bo.Menu.Contactos.Importar"]
                    };

                    SearchCustomer.ChildItems.Add(ImportarContactosMenu);
                }

                MenuItem ReportesContactoMenu = new MenuItem()
                {
                    Selectable = false,
                    Text = LocalizationProvider.Instance["Bo.Menu.Reportes"]
                };

                SearchCustomer.ChildItems.Add(ReportesContactoMenu);

                ReportingConfiguration reportConfigVentasPorCliente = reportingConfigurationList.Where(r => r.Nombre == formatReporte(paisPorDefecto, "Crm.{0}.VentasPorCliente")).SingleOrDefault();
                AddReporteToMenu(ReportesContactoMenu, reportConfigVentasPorCliente);

                ReportingConfiguration reportConfigVentasVIP = reportingConfigurationList.Where(r => r.Nombre == formatReporte(paisPorDefecto, "Crm.{0}.VentasClientesVip")).SingleOrDefault();
                AddReporteToMenu(ReportesContactoMenu, reportConfigVentasVIP);

                ReportingConfiguration reportConfigRangoEtareo = reportingConfigurationList.Where(r => r.Nombre == formatReporte(paisPorDefecto, "Crm.{0}.VentasRangoEtareo")).SingleOrDefault();
                AddReporteToMenu(ReportesContactoMenu, reportConfigRangoEtareo);


                MenuItem PDVMenu = new MenuItem()
               {
                   Text = LocalizationProvider.Instance["Bo.Menu.PuntosDeVenta"],
                   Selectable = false
               };

                this.NavigationMenu.Items.Add(PDVMenu);

                MenuItem ReportesPDVMenu = new MenuItem()
                {
                    Selectable = false,
                    Text = LocalizationProvider.Instance["Bo.Menu.Reportes"]
                };

                PDVMenu.ChildItems.Add(ReportesPDVMenu);

                ReportingConfiguration reportConfigRankingAsociacion = reportingConfigurationList.Where(r => r.Nombre == formatReporte(paisPorDefecto, "Crm.{0}.RankingDeAsociacionPorLocal")).SingleOrDefault();
                AddReporteToMenu(ReportesPDVMenu, reportConfigRankingAsociacion);

                ReportingConfiguration reportConfigRankingAsociacionMensual = reportingConfigurationList.Where(r => r.Nombre == formatReporte(paisPorDefecto, "Crm.{0}.RankingDeAsociacionPorLocalMensual")).SingleOrDefault();
                AddReporteToMenu(ReportesPDVMenu, reportConfigRankingAsociacionMensual);

                ReportingConfiguration reportConfigOperaciones = reportingConfigurationList.Where(r => r.Nombre == formatReporte(paisPorDefecto, "Crm.{0}.OperacionesPorPDVConLineas")).SingleOrDefault();
                AddReporteToMenu(ReportesPDVMenu, reportConfigOperaciones);

                MenuItem CampanasMenu = new MenuItem()
                {
                    NavigateUrl = "~" + MiscClass.UrlPlanDeMarketingList,
                    Text = LocalizationProvider.Instance["Bo.Menu.PlanesDeMarketing"]                    
                };

                this.NavigationMenu.Items.Add(CampanasMenu);

                CampanasMenu.Selectable = HasPermissionFor(CrmSecurity.MARKETINGPLAN_SEARCH);

                if (HasPermissionFor(CrmSecurity.MARKETINGPLAN_SEARCH))
                {
                    MenuItem CampanasMenu2 = new MenuItem()
                    {
                        NavigateUrl = "~" + MiscClass.UrlPlanDeMarketingList,
                        Text = LocalizationProvider.Instance["Bo.Menu.PlanesDeMarketing"]
                    };

                    CampanasMenu.ChildItems.Add(CampanasMenu2);
                }

                if (HasPermissionFor(CrmSecurity.DISTRIBUTIONLIST_SEARCH) || HasPermissionFor(CrmSecurity.DISTRIBUTIONLIST_MANAGE))
                {
                    MenuItem ListasDeDistribucionMenu = new MenuItem()
                    {
                        NavigateUrl = "~" + MiscClass.UrlListaDeDistribucionList,
                        Text = LocalizationProvider.Instance["Bo.Menu.ListasDeDistribucion"]
                    };

                    CampanasMenu.ChildItems.Add(ListasDeDistribucionMenu);
                }

                if (HasPermissionFor(CrmSecurity.MARKETINGACTION_SEARCH))
                {
                    MenuItem AccionesDeMarketingMenu = new MenuItem()
                    {
                        NavigateUrl = "~" + MiscClass.UrlAccionDeMarketingList,
                        Text = LocalizationProvider.Instance["Bo.Menu.AccionesDeMarketing"]
                    };

                    CampanasMenu.ChildItems.Add(AccionesDeMarketingMenu);

                    var accionesDeMkt = Enum.GetValues(typeof(DiscriminadorAccionDeMarketing));
                    foreach (var accionMkt in accionesDeMkt)
                    {
                        MenuItem AccionesDeMarketingInternoMenu = new MenuItem()
                        {
                            NavigateUrl = "~" + MiscClass.UrlAccionDeMarketingList + string.Format("?discriminadorId={0}", (int)accionMkt),
                            Text = UIHelper.GetEnumDescription(accionMkt)
                        };

                        AccionesDeMarketingMenu.ChildItems.Add(AccionesDeMarketingInternoMenu);
                    }
                }

                MenuItem ReportesMarketingMenu = new MenuItem()
                {
                    Selectable = false,
                    Text = LocalizationProvider.Instance["Bo.Menu.Reportes"]
                };

                CampanasMenu.ChildItems.Add(ReportesMarketingMenu);

                // Aplicantes a promociones
                ReportingConfiguration reportConfigAppPromo = reportingConfigurationList.Where(r => r.Nombre == formatReporte(paisPorDefecto, "Crm.{0}.AplicantesAPromocion")).SingleOrDefault();
                AddReporteToMenu(ReportesMarketingMenu, reportConfigAppPromo);                    

                // Promociones
                ReportingConfiguration reportConfigPromo = reportingConfigurationList.Where(r => r.Nombre == formatReporte(paisPorDefecto, "Crm.{0}.Promociones")).SingleOrDefault();
                AddReporteToMenu(ReportesMarketingMenu, reportConfigPromo);               

                MenuItem AdministracionMenu = new MenuItem()
                {
                    Selectable = false,
                    Text = LocalizationProvider.Instance["Bo.Menu.Administracion"]
                };

                this.NavigationMenu.Items.Add(AdministracionMenu);

                if (HasPermissionFor(CrmSecurity.COUNTRY_MANAGE) || HasPermissionFor(CrmSecurity.COUNTRY_SEARCH))
                {
                    MenuItem PaisesMenu = new MenuItem()
                    {
                        NavigateUrl = "~" + MiscClass.UrlPaisList,
                        Text = LocalizationProvider.Instance["Bo.Menu.Paises"]
                    };

                    AdministracionMenu.ChildItems.Add(PaisesMenu);
                }

                if (HasPermissionFor(CrmSecurity.CATEGORY_MANAGE) || HasPermissionFor(CrmSecurity.CATEGORY_SEARCH))
                {
                    MenuItem CategoriasMenu = new MenuItem()
                    {
                        NavigateUrl = "~/App/CategoriaList.aspx",
                        Text = LocalizationProvider.Instance["Bo.Menu.Categorias"]
                    };

                    AdministracionMenu.ChildItems.Add(CategoriasMenu);
                }

                if (HasPermissionFor(CrmSecurity.DOCUMENTTYPE_MANAGE) || HasPermissionFor(CrmSecurity.DOCUMENTTYPE_SEARCH))
                {
                    MenuItem TiposDeDocumentoMenu = new MenuItem()
                    {
                        NavigateUrl = "~/App/FuncionalidadNoImplementada.aspx",
                        Text = LocalizationProvider.Instance["Bo.Menu.TipoDocumento"]
                    };

                    AdministracionMenu.ChildItems.Add(TiposDeDocumentoMenu);
                }

                if (HasPermissionFor(CrmSecurity.PDV_MANAGE) || HasPermissionFor(CrmSecurity.PDV_SEARCH))
                {
                    MenuItem puntoVtaMenu = new MenuItem()
                    {
                        NavigateUrl = "~" + MiscClass.UrlPuntoDeVentaList,
                        Text = LocalizationProvider.Instance["Bo.Menu.PuntosDeVenta"]
                    };

                    AdministracionMenu.ChildItems.Add(puntoVtaMenu);
                }

                if (HasPermissionFor(CrmSecurity.BITACORA_MSGTYPE_MANAGE))
                {
                    MenuItem tipoMensajeMenu = new MenuItem()
                    {
                        NavigateUrl = "~" + MiscClass.UrlTipoMensajeBitacoraList,
                        Text = LocalizationProvider.Instance["Bo.Menu.TipoMensajeBitacora"]
                    };

                    AdministracionMenu.ChildItems.Add(tipoMensajeMenu);
                }

                if (HasPermissionFor(CrmSecurity.BRAND_MANAGE))
                {
                    MenuItem configuracionCompanyMenu = new MenuItem()
                   {
                       NavigateUrl = "~" + MiscClass.UrlCompanyConfigurationEdit,
                       Text = LocalizationProvider.Instance["Bo.Menu.ConfiguracionEmpresa"]
                   };

                    AdministracionMenu.ChildItems.Add(configuracionCompanyMenu);
                }

                if (HasPermissionFor(CrmSecurity.LANGUAJE_MANAGE))
                {
                    MenuItem lenguajeMenu = new MenuItem()
                    {
                        NavigateUrl = "~/App/LenguajeList.aspx",
                        Text = LocalizationProvider.Instance["Bo.Menu.Lenguaje"]
                    };

                    AdministracionMenu.ChildItems.Add(lenguajeMenu);
                }

                MenuItem AccionesDeMarketingAdminMenu = new MenuItem()
                {
                    Selectable = false,
                    Text = LocalizationProvider.Instance["Bo.Menu.PlanesDeMarketing"]
                };

                AdministracionMenu.ChildItems.Add(AccionesDeMarketingAdminMenu);

                if (HasPermissionFor(CrmSecurity.MANAGE_PROMO_RULES))
                {
                    MenuItem ReglasListMenu = new MenuItem()
                    {
                        NavigateUrl = "~" + MiscClass.UrlReglaList,
                        Text = LocalizationProvider.Instance["Bo.Menu.Reglas"]
                    };

                    AccionesDeMarketingAdminMenu.ChildItems.Add(ReglasListMenu);
                }

                if (HasPermissionFor(CrmSecurity.MANAGE_MKT_COMMUNICATIONS_CONFIG))
                {
                    MenuItem ConfiguracionMarketingMenu = new MenuItem()
                    {
                        NavigateUrl = "~" + MiscClass.UrlMarketingConfiguracionList,
                        Text = LocalizationProvider.Instance["Bo.Menu.MarketingConfiguracion"]
                    };

                    AccionesDeMarketingAdminMenu.ChildItems.Add(ConfiguracionMarketingMenu);
                }

                if (HasPermissionFor(CrmSecurity.MANAGE_MKT_COMMUNICATIONS_TYPES))
                {
                    MenuItem TipoMarketingMenu = new MenuItem()
                    {
                        NavigateUrl = "~" + MiscClass.UrlAccionDeMarketingComunicacionTipoList,
                        Text = LocalizationProvider.Instance["Bo.Menu.MarketingComunicacionTipo"]
                    };

                    AccionesDeMarketingAdminMenu.ChildItems.Add(TipoMarketingMenu);
                }
            }
        }
    }
}
